package org.example.wumeng.controller;

import org.example.wumeng.service.T_bookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.example.wumeng.pojo.Book;
import org.example.wumeng.pojo.Result;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/books")
@CrossOrigin(origins = "*", maxAge = 3600)
public class T_bookController {

    @Autowired
    private T_bookService bookService;

    /**
     * 分页查询医书列表
     */
    @GetMapping
    public Result<List<Book>> getList(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "author", required = false) String author,
            @RequestParam(value = "category", required = false) String category) {
        try {
            title = (title != null && !title.trim().isEmpty()) ? title.trim() : null;
            author = (author != null && !author.trim().isEmpty()) ? author.trim() : null;
            category = (category != null && !category.trim().isEmpty()) ? category.trim() : null;

            Map<String, Object> result = bookService.getList(page, size, title, author, category);
            @SuppressWarnings("unchecked")
            List<Book> books = (List<Book>) result.get("data");
            Long total = (Long) result.get("total");

            return new Result<>(200, "查询成功", books, total);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("查询医书列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取医书详情
     */
    @GetMapping("/{id}")
    public Result<Book> getById(@PathVariable Long id) {
        try {
            Book book = bookService.getById(id);
            return new Result<>(200, "查询成功", book, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.error("查询医书详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取医书全文内容
     */
    @GetMapping("/{id}/full-content")
    public Result<String> getFullContent(@PathVariable Long id) {
        try {
            String fullContent = bookService.getFullContentById(id);
            if (fullContent == null || fullContent.trim().isEmpty()) {
                return new Result<>(200, "该医书暂无全文内容", "", null);
            }
            return new Result<>(200, "获取成功", fullContent, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取医书全文内容失败: " + e.getMessage());
        }
    }

    /**
     * 创建医书
     */
    @PostMapping
    public Result<Long> create(@RequestBody Book book) {
        try {
            Long id = bookService.create(book);
            return new Result<>(200, "创建成功", id, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("创建医书失败: " + e.getMessage());
        }
    }

    /**
     * 更新医书信息
     */
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id, @RequestBody Book book) {
        try {
            bookService.update(id, book);
            return new Result<>(200, "更新成功", null, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新医书失败: " + e.getMessage());
        }
    }


    /**
     * 删除医书
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        try {
            bookService.delete(id);
            return new Result<>(200, "删除成功", null, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("删除医书失败: " + e.getMessage());
        }
    }

    /**
     * 根据作者统计医书数量
     */
    @GetMapping("/count/author")
    public Result<Long> countByAuthor(@RequestParam String author) {
        try {
            if (author == null || author.trim().isEmpty()) {
                return Result.badRequest("作者参数不能为空");
            }

            Long count = bookService.countByAuthor(author.trim());
            return new Result<>(200, "统计完成", count, null);

        } catch (Exception e) {
            return Result.error("统计医书数量失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类统计医书数量
     */
    @GetMapping("/count/category")
    public Result<Long> countByCategory(@RequestParam String category) {
        try {
            if (category == null || category.trim().isEmpty()) {
                return Result.badRequest("分类参数不能为空");
            }

            Long count = bookService.countByCategory(category.trim());
            return new Result<>(200, "统计完成", count, null);

        } catch (Exception e) {
            return Result.error("统计医书数量失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类查询医书
     */
    @GetMapping("/category/{category}")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public Result<List<Book>> getByCategory(
            @PathVariable String category,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            if (category == null || category.trim().isEmpty()) {
                return Result.badRequest("分类参数不能为空");
            }
            return bookService.getByCategory(category.trim(), page, size);
        } catch (Exception e) {
            return Result.error("查询分类医书失败: " + e.getMessage());
        }
    }

    /**
     * 获取分类统计
     */
    @GetMapping("/category/statistics")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public Result<List<Map<String, Object>>> getCategoryStatistics() {
        try {
            return bookService.getCategoryStatistics();
        } catch (Exception e) {
            return Result.error("获取分类统计失败: " + e.getMessage());
        }
    }
}